package org.syncsoft.overalt.gui.impl.window.viewHistory;

import java.util.Collection;
import java.util.HashSet;

import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.JTextComponent;

import org.syncsoft.overalt.common.api.Resource;
import org.syncsoft.overalt.domain.document.entity.History;
import org.syncsoft.overalt.gui.api.window.AbstractWindow;
import org.syncsoft.overalt.gui.impl.componentPlugin.HistoryListComponentPlugin;
import org.syncsoft.overalt.gui.impl.componentPlugin.TextComponentPlugin;
import org.syncsoft.overalt.gui.util.BuildFormWindow;

/**
 * 
 * @author tptfc
 *
 */
public class ViewHistoryWindow extends AbstractWindow {
	private Collection<History> histories;
	
	{
		setHistories(new HashSet<History>());
	}
	
	public ViewHistoryWindow(ViewHistoryWindowController controller) {
		super(controller);
	}

	public ViewHistoryWindow(int width, int height, ViewHistoryWindowController controller) {
		super(width, height, controller);
	}

	@Override
	protected void buildWindow() {
		BuildFormWindow build = new BuildFormWindow(getPanel());
		setTitle(Resource.getProperty("overalt.label.history"));
	
		JLabel label;
		
		JList list = newHistoryList("history", getHistories());
		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		list.addListSelectionListener(new HistoryListSelectionListener());
		label = new JLabel(Resource.getProperty("overalt.label.history"));
		
		build.add(label, list);
		
		label = new JLabel(Resource.getProperty("overalt.label.description"));
		JTextArea text = newTextArea("description");
		text.setEditable(false);
		build.add(label, text);
		
		addSaveAndCancelButtons(build);
	}
	
	private class HistoryListSelectionListener implements ListSelectionListener {
		@Override
		public void valueChanged(ListSelectionEvent e) {
			int index = e.getLastIndex();
			
			History history = getHistoryFromListByIndex("history", index);
			if (history != null) {
				JTextComponent text = getTextArea("description");
				text.setText(history.getDescription());
			}
		}
		
	}
	
	
	private JTextComponent getTextArea(String key) {
		return getComponentPlugin(TextComponentPlugin.class).getTextComponent(key);
	}
	
	private History getHistoryFromListByIndex(String key, int index) {
		return getComponentPlugin(HistoryListComponentPlugin.class).getEntity(key, index);
	}
	
	private JList newHistoryList(String key, Collection<History> histories) {
		return getComponentPlugin(HistoryListComponentPlugin.class).newList(key, histories);
	}

	private Collection<History> getHistories() {
		return histories;
	}

	void setHistories(Collection<History> histories) {
		this.histories = histories;
	}
}
